var Player = Class.create({
	CARD_TYPE : ['arm','attack','arm'],
	initialize : function(){
		this.id;
		this.cards;
		this.arms;
		this.hps;
		this.selectedCard;
		this.cardsContainerDivId;
		this.userArray;
		this.userDistance;	  
		this.attackUser;
		this.attackDistance;
		this.allCardCount;
		this.userMapArray;
		this.isReceiveAttack;
		this.beSentUser;
		this.lifeCount;
		this.waitReceive;
		this.isActive;
		this.selectableCardType;
		this.roomId;
		this.receivedCard;
		this.activecards;
		this.user;
		this.isDoPolicy;
		this.isDoDropCard;
		this.selectedCards;
		this.dropableCount;
		this.policyButtonId;
		this.isDoSaving;
	},
	init : function(o){
		this.id = o.id;
		this.roomId = o.roomId;
		this.cards = [];
		this.attackDistance = 1;
		this.allCardCount = 0;
		EventBus.subscribe("card.selected", this._callbackSelectCard.bind(this));
		EventBus.subscribe("card.double.click", this._callbackDoubleClickCard.bind(this));
		ddManager.registerDDContainer("arm_card",
			["arm"], {}, this._callbackArmCardDDEnd.bind(this));

		this.secs;
		this.timerID = null;
		this.timerRunning = false;
		this.delay = 1000;
		this.isReceiveAttack = false;
		this.user = o['user'];
		this.lifeCount = o['user'].blood;
		this.waitReceive = false;
		this.isActive = false;
		this.isDoPolicy = false;
		this.isDoDropCard = false;
		this.isDoSaving = false;
		this.activecards = [];
		this.selectedCards = [];
		this.dropableCount = 0;
		this.attackUser = [];

		this.finishPlay = Utility.unDuplicateFunction(this.finishPlay, this);
	},
	setUserAttack : function(usersArary, userMapArray){
		this.userArray = usersArary;
		this.userMapArray = userMapArray;
	},
	setActive : function(active){
	    if(active == this.isActive) return;
		this.isActive = active;
		//alert("active is " + this.isActive);
		if(this.isActive){
			this.InitializeTimer();
			$('finish_play').disabled = false;
//			this.setUserMessage("Now is active, can play card!");
		    var room = ComponentManager.getComponentById(this.roomId);
		    if(room){
				room.showCurrentActiveUser(this.user);
		    }
		}else{
			this.StopTheClock();
			this.clearReceiveArea()
			$('finish_play').disabled = true;
//			this.setUserMessage("Now is not active, can not play card!");
		}
		if(this.cards){
			this.redrawCards(this.cardsContainerDivId, this.cards);
		}
	},
	setUserMessage : function(msg){
		var msgElement = $('user_message');
		if(msg){
			msgElement.innerHTML = "<font color='#ff0000'>"+msg+"</font>";
			setTimeout(this.setUserMessage.bind(this, null), 2000);
		}
		else{
			msgElement.innerHTML = "";
		}
	},
	setActiveCards : function(cards){
		this.activecards = cards;
	},
	readyToPlay : function(){
		this.setActive(true);
		this.setUserMessage("Now is active, can play card!");
		//$('finish_play').disabled = false;
	},
	finishPlay : function(){
		//$('finish_play').disabled = true;
		this.clearSelectedStyle();
		this.StopTheClock();
        if(this.isReceiveAttack || this.isDoSaving){
			//this.StopTheClock();
			this.failToDoMatchCard();
        }
        else{
        	if(this.isDoDropCard){
				this.dropCards();
        	}
        	//else if(this.isDoSaving){
        	//	RoomService.userDead();
        	//}
        	else{
	        	if(this.isDoPolicy){
	        		this.isDoPolicy = false;
					for(var j=0; j<this.selectedCards.length; j++){
						var element = document.getElementById(this.selectedCards[j].id);
						element.style.border = "";
					}
					this.selectedCards = [];
	        	}
			    var room = ComponentManager.getComponentById(this.roomId);
				room.finishPlay(this.id);
        	}
			
        }
	},
	getUserIdByName : function(userName){
		if(this.attackUser && this.userMapArray){
			for(var i=0; i<this.attackUser.length; i++){
				var user = this.attackUser[i];
				if(this.userMapArray[user]){
					if(this.userMapArray[user].name == userName){
						return user;
					}
				}
			}
		}
	},
	registerAttackableUser : function(userList){
		this.attackUser = [];
		
		for(var i=0; i<this.userArray.length; i++){
			var user = this.userArray[i];
			var userName = this.userMapArray[user].name;
			for(var j=0; j<userList.length; j++){
				if( userList[j].name == userName ){
					this.attackUser.push(user);
				}
			}
		}
		/*
		var attackableUser = [];
		//ASC check
		var order = 0 + distance;
		var looplen =  distance<userlist.length?distance:userlist.length-1;
		for(var i=1; i<=looplen; i++){
			var user = userlist[i];
			if(!attackableUser[user]){
				attackableUser[user] = user;
			}
		}
		//DESC check
		order = userlist.length - distance;
		var looplen =  userlist.length-distance>0?userlist.length-distance:1;
		for(var i=userlist.length-1; i>=looplen; i--){
			var user = userlist[i];
			if(!attackableUser[user]){
				attackableUser[user] = user;
			}
		}
		for( var i in attackableUser ){
			var user = 	attackableUser[i];
			if (typeof user == "string") {
				this.attackUser.push(user);
			}
		}
		*/
		for( var i=0; i<this.attackUser.length; i++){
			var user = this.attackUser[i];
			//register DD
			ddManager.registerDDContainer(user + "_card_area",
				["attack_1"], {}, this._callbackAttackCardDDEnd.bind(this, user));
		}
	},
	registerAttackableUserByUserName : function(userList){
		this.attackUser = [];
		
		for(var i=0; i<this.userArray.length; i++){
			var user = this.userArray[i];
			var userName = this.userMapArray[user].name;
			for(var j=0; j<userList.length; j++){
				if( userList[j] == userName ){
					this.attackUser.push(user);
				}
			}
		}
		for( var i=0; i<this.attackUser.length; i++){
			var user = this.attackUser[i];
			//register DD
			ddManager.registerDDContainer(user + "_card_area",
				["attack_1"], {}, this._callbackAttackCardDDEnd.bind(this, user));
		}
		RoomService.finishedRegisterAttack();
	},
	drawCards : function(cardId, aryCards){
		this.cardsContainerDivId = cardId;
		var existedCardCnt = this.allCardCount;
		for(var i=0; i<aryCards.length; i++){
			var card = aryCards[i];
			//get card index base on existed cards
			var cardCnt = i + existedCardCnt;
			var divId  = this.id + '_card_' + cardCnt;
			var player = this;
			var onDivClick = function(){
				player.cardClick(divId);
			}
			var newCard = new ObjectCard();
			var conf = {};
			conf.id = divId;
			conf.cardId = card["id"];
			conf.title = card["name"];
			conf.content = card["displayName"];
			conf.distance = card["distance"];
			conf.cardType = card["cardType"];
			conf.suite = card["suite"];
			conf.rank = card["rank"];
			conf.parentId = cardId;
			conf.className = 'cardDisableClass';
			conf.active = false;
			if(this.activecards){
				var cardActive = false;
				for(var j=0; j<this.activecards.length; j++){
					if(conf.cardType == this.activecards[j]){
						cardActive = true;
						break;
					}
					else if(conf.title == this.activecards[j]){
						cardActive = true;
						break;
					}
					if(cardActive){
						conf.className = 'cardClass';
						conf.active = true;
					}
					else{
						conf.className = 'cardDisableClass';
						conf.active = false;
					}
				}
			}
			//conf.className = 'cardClass';
			//conf.onClick = onDivClick;
			//conf.cardType = this.CARD_TYPE[i%2];
			newCard.init(conf);
			newCard.drawCard();
			this.cards.push(newCard);
		}
		this.allCardCount += aryCards.length;
		//register attack user
		//this.registerAttackableUser(this.userArray, this.attackDistance);
	},
	
	refreshAllCards : function(cardId, aryCards){
		var element = document.getElementById(cardId);
		element.innerHTML = "";
		this.cardsContainerDivId = cardId;
		var existedCardCnt = 0;
		for(var i=0; i<aryCards.length; i++){
			var card = aryCards[i];
			//get card index base on existed cards
			var cardCnt = i + existedCardCnt;
			var divId  = this.id + '_card_' + cardCnt;
			var player = this;
			var onDivClick = function(){
				player.cardClick(divId);
			}
			var newCard = new ObjectCard();
			var conf = {};
			conf.id = divId;
			conf.cardId = card["id"];
			conf.title = card["name"];
			conf.content = card["displayName"];
			conf.distance = card["distance"];
			conf.cardType = card["cardType"];
			conf.suite = card["suite"];
			conf.rank = card["rank"];
			conf.parentId = cardId;
			conf.className = 'cardDisableClass';
			conf.active = false;
			if(this.activecards){
				var cardActive = false;
				for(var j=0; j<this.activecards.length; j++){
					if(conf.cardType == this.activecards[j]){
						cardActive = true;
						break;
					}
					else if(conf.title == this.activecards[j]){
						cardActive = true;
						break;
					}
					if(cardActive){
						conf.className = 'cardClass';
						conf.active = true;
					}
					else{
						conf.className = 'cardDisableClass';
						conf.active = false;
					}
				}
			}
			newCard.init(conf);
			newCard.drawCard();
			this.cards.push(newCard);
		}
		this.allCardCount = aryCards.length;
	},

	recieveRoleCard : function(card) {
		this.roleCard = card;
		$('user1_role_name').innerHTML = card.name;
	    var room = ComponentManager.getComponentById(this.roomId);
		if(this.roleCard.name == "King" && room.getRoomState() < 2){
			$('div_room_game_start').style.display = "";
			
		}	
		room.setRoomState(2);
	},
	
	recieveCharacterCard : function(card) {
		this.characterCard = card;
		$('user1_character_name').innerHTML = card.name;
		$('user1_character_name').title = card.policyDescription;
	    var room = ComponentManager.getComponentById(this.roomId);
		if(this.roleCard.name == "King"){
			room.setGameStart();
			//$('btn_game_start').disabled = false;
		}
		//show policy button
		var policyList = card.clientPolicyList;
		if(policyList != null ){
			for(var i=0; i<policyList.length; i++){
				if(!policyList[i]) continue;
				//alert("policy id:" + policyList[i].id + "policy name:" +policyList[i].name)
				this.showPolicyButton(policyList[i].generatedId, policyList[i].name, card.policyDescription);
			}
		}
		room.setRoomState(3);
		
	},
	showPolicyButton : function(buttonId, buttonName, description){
		var element = document.getElementById('policy_button');
		element.innerHTML = "";

		//var spaceElement = document.createElement('DIV');
		//spaceElement.style.width = "3px";
		//element.appendChild(spaceElement);
		
		var suiteElement = document.createElement('DIV');
		suiteElement.title = description;
		suiteElement.setAttribute("id", buttonId);
		suiteElement.innerHTML = "<font size='-2'>"+buttonName+"</font>";
		suiteElement.style.border = "solid 1px";
		suiteElement.style.background = "#99FFFF";
		//suiteElement.style.display = "inline-block";
		suiteElement.style.width = "50px";
		var player = this;
		suiteElement.onclick = function() {player.characterPolicy(buttonId);};
		element.appendChild(suiteElement);
	},
	
	receiveCard : function(aryCards){
		var existedCardCnt = this.allCardCount;
		for(var i=0; i<aryCards.length; i++){
			var card = aryCards[i];
			//get card index base on existed cards
			var cardCnt = i + existedCardCnt;
			var divId  = this.id + '_card_' + cardCnt;
			var player = this;
			var onDivClick = function(){
				player.cardClick(divId);
			}
			var newCard = new ObjectCard();
			var conf = {};
			conf.id = divId;
			conf.cardId = card["id"];
			conf.title = card["name"];
			conf.content = card["displayName"];
			conf.distance = card["distance"];
			conf.cardType = card["cardType"];
			conf.suite = card["suite"];
			conf.rank = card["rank"];
			conf.parentId = 'user1_main_card';
			conf.className = 'cardDisableClass';
			conf.active = false;
			if(this.activecards){
				var cardActive = false;
				for(var j=0; j<this.activecards.length; j++){
					if(conf.cardType == this.activecards[j]){
						cardActive = true;
						break;
					}
					else if(conf.title == this.activecards[j]){
						cardActive = true;
						break;
					}
					if(cardActive){
						conf.className = 'cardClass';
						conf.active = true;
					}
					else{
						conf.className = 'cardDisableClass';
						conf.active = false;
					}
				}
			}
			//conf.className = 'cardClass';
			//conf.onClick = onDivClick;
			//conf.cardType = this.CARD_TYPE[i%2];
			newCard.init(conf);
			newCard.drawCard();
			this.cards.push(newCard);
		}
		this.allCardCount += aryCards.length;
	},
	cardClick : function(divId){
		EventBus.publish("card.selected", {id:divId});
	},
	cardDBClick : function(divId){
		EventBus.publish("card.double.click", {id:divId});
	},
	equipCard : function(){
		if (!this.arms)
		{
			this.arms = [];
		}
		/*
		//redraw arm area
		var index = this.arms.length;
		var conf = this.selectedCard.conf;
		conf.parentId = "arm_" + index;
		var card = new ObjectCard();
		card.init(conf);
		card.resetCardDraw("arm_" + index);
		this.arms[index] = card;
		//redo player distance
		if(this.selectedCard.title == "attackhorse"){
			this.attackDistance += conf.distance;
		}else if(this.selectedCard.title == "defendhorse"){
//			this.attackDistance = conf.distance;
		}else{
			this.attackDistance = conf.distance;
		}
		*/
		//equipment card to server
		var targetuser = new Array();
		targetuser[0] = this.user.name;
		var room = ComponentManager.getComponentById(this.roomId);
		var dataVersion = room.getDataVersion();
		RoomService.sendCard("current_player_instance", targetuser, this.selectedCard.cardId, dataVersion);
//		$('send_data_version').innerHTML = dataVersion;

		//redraw cards area
//		this.removeAndrefreshCards(this.selectedCard.id, true);
//		this.clearSelectedStyle();
		this.InitializeTimer();
		//this.cancelCard();
	},
	equipCardByDrag : function(equipmentCard){
		if (!this.arms)
		{
			this.arms = [];
		}
		/*
		//redraw arm area
		var index = this.arms.length;
		var conf = equipmentCard.conf;
		conf.parentId = "arm_" + index;
		var card = new ObjectCard();
		card.init(conf);
		card.resetCardDraw("arm_" + index);
		this.arms[index] = card;
		//redo player distance
		if(equipmentCard.title == "attackhorse"){
			this.attackDistance += conf.distance;
		}else{
			this.attackDistance = conf.distance;
		}
		*/
		//equipment card to server
		var targetuser = new Array();
		targetuser[0] = this.user.name;
		var room = ComponentManager.getComponentById(this.roomId);
		var dataVersion = room.getDataVersion();
		RoomService.sendCard("current_player_instance", targetuser, equipmentCard.cardId, dataVersion);
//		$('send_data_version').innerHTML = dataVersion;

		//redraw cards area
//		this.removeAndrefreshCards(equipmentCard.id, true);
//		this.clearSelectedStyle();
		this.InitializeTimer();
		//this.cancelCard();
	},
	refreshEquipmentCard : function(aryCards){
		this.arms = [];
		this.attackDistance = 1;
		var hadAttackHorse = false;
		var hadArm = false;
		for(var i=0; i<aryCards.length; i++){

			var element = document.getElementById("arm_" + i);
			element.className = 'currentArmClass';
			element.innerHTML = "";

			var card = aryCards[i];
			var newCard = new ObjectCard();
			var conf = {};
			conf.id = "equipment_card_" + i;
			conf.parentId = "arm_" + i;
			conf.cardId = card["id"];
			conf.title = card["name"];
			conf.content = card["displayName"];
			conf.distance = card["distance"];
			conf.cardType = card["cardType"];
			conf.suite = card["suite"];
			conf.rank = card["rank"];
			conf.className = 'cardDisableClass';
			conf.active = false;
			newCard.init(conf);
			newCard.drawCard();
			//newCard.resetCardDraw(parentId);
			this.arms[i] = newCard;
			if(newCard.title == "attackhorse"){
				hadAttackHorse = true;
			}else if(newCard.title == "arm"){
				hadArm = true;
			}
		}
		//redo player distance
		if(hadArm){
			this.attackDistance = 2;
		}
		if(hadAttackHorse){
			this.attackDistance += 1;
		}
	},
	replaceEquipmentCard : function(card){
		var index = this.arms.length-1;
		this.arms.pop();
		var element = document.getElementById("arm_" + index);
		element.className = 'armClass';
		element.innerHTML = "";
		//card.removeCardDraw("arm_" + index);
	},
	okCard : function(){
		if(this.isDoPolicy){
			this.discardPolicyCards();
			this.StopTheClock();
		}
		else if(this.isDoDropCard ){
			if(this.dropableCount > 0){
				if( !this.selectedCards || this.selectedCards.length != this.dropableCount){
					alert("please select " + this.dropableCount + " drop cards!");
					return;
				}
				else{
					this.dropCards(this.selectedCards);
					this.StopTheClock();
				}
			}
		}
		//else if(this.isDoSaving){
		//}
		else{
			if(this.selectedCard){
				if(this.selectedCard.cardType == "arm")	{
					this.equipCard();
				}
				else if(this.isReceiveAttack && this.selectedCard.title == "defend"){
					var receiveDiv = "user1_card_receive_area";
					var conf = this.selectedCard.conf;
					conf.parentId = receiveDiv;
					var card = new ObjectCard();
					card.init(conf);
					card.drawUsedCard();
					this.discard(this.beSentUser, card);
					//redraw cards area
//					this.removeAndrefreshCards(this.selectedCard.id, true);
					//this.clearSelectedStyle();
					this.isReceiveAttack = false;
					this.StopTheClock();
				}
				else if(this.selectedCard.title == "milk"){
					if(this.lifeCount < 5){
						var receiveDiv = "user1_card_receive_area";
						var conf = this.selectedCard.conf;
						conf.parentId = receiveDiv;
						var card = new ObjectCard();
						card.init(conf);
						card.drawUsedCard();
						this.discard(this.user.name, card);
						//this.addLife();
//						this.removeAndrefreshCards(this.selectedCard.id, true);
						//this.clearSelectedStyle();
						this.StopTheClock();
					}
				}
			}
		}
	},
	cancelCard : function(){
		this.clearSelectedStyle();
		this.StopTheClock();
		if(this.isReceiveAttack){
			//this.cutLife();
			this.failToDoMatchCard();
		}
		$(this.policyButtonId).style.border="";
		this.isDoPolicy = false;
	},
	clearSelectedStyle : function(){
		if(this.selectedCard){
			var element = document.getElementById(this.selectedCard.id);
			if(element){
				var armArea = document.getElementById("arm_card");
				if(element.style.border && element.style.border != ""){
					element.style.border = "";
					armArea.style.border = "solid 1px";
				}
			}
			this.selectedCard = null;
		}
	},
	redrawCards : function(parentId, cards){
		var element = document.getElementById(parentId);
		element.innerHTML = "";
		for(var i=0; i<cards.length; i++){
			var cardActive = false;
			if(this.isActive){
				for(var j=0; j<this.activecards.length; j++){
					if(cards[i].cardType == this.activecards[j]){
						cardActive = true;
						break;
					}
					else if(cards[i].title == this.activecards[j]){
						cardActive = true;
						break;
					}
				}
				if(cardActive){
					cards[i].setClassName('cardClass');
					cards[i].setActive(true);
				}
				else{
					cards[i].setClassName('cardDisableClass');
					cards[i].setActive(false);
				}
			}
			else{
				cards[i].setClassName('cardDisableClass');
				cards[i].setActive(false);
			}
			cards[i].drawCard();
		}
		//register attack user
		//this.registerAttackableUser(this.userArray, this.attackDistance);
	},
	removeAndrefreshCards : function(removeId, isRefresh){
		for(var i=0; i<this.cards.length; i++){
			if(this.cards[i].id == removeId){
				this.cards.splice(i,1);
				break;
			}
		}
		if(isRefresh){
			this.redrawCards(this.cardsContainerDivId, this.cards);
		}
	},
	_callbackSelectCard : function(event, message, componentId){
		if(this.isDoPolicy || this.isDoDropCard){
		}
		for(var i=0; i<this.cards.length; i++){
			var div = this.cards[i];
			var element = document.getElementById(div.id);
			if(element){
				if(div.id != message.id){
					if(this.isDoPolicy || this.isDoDropCard){
					}
					else{
						if(element.style.border && element.style.border != ""){
							element.style.border = "";
						}
					}
				}
				else{
					var element = document.getElementById(div.id);
					var armArea = document.getElementById("arm_card");
					if(this.isDoPolicy || this.isDoDropCard){
						var isExisted = false;
						for(var j=0; j<this.selectedCards.length; j++){
							if(this.cards[i].id == this.selectedCards[j].id){
								this.selectedCards.splice(j,1);
								isExisted = true;
								break;
							}
						}
						if(!isExisted){
							this.selectedCards.push(this.cards[i])
							element.style.border = "solid 2px #0000ff";
						}
						else{
							element.style.border = "";
						}
					}
					else{
						if(this.selectedCard){
							element.style.border = "";
							armArea.style.border = "solid 1px";
							//alert attack able area
							if(this.selectedCard.distance > 0){
								this.alertAttackableArea(0);
							}
							this.selectedCard = null;
						}
						else{
							this.selectedCard = this.cards[i];
							element.style.border = "solid 2px #0000ff";
							if(element.getAttribute("w:cardType") == "arm"){
								armArea.style.border = "dotted 2px #0000EE";
							}
							else{
								armArea.style.border = "solid 1px";
								//alert attack able area
								if(this.selectedCard.distance > 0){
									this.alertAttackableArea(1);
								}
								this.setUserMessage("Drag drop it to target user!");
							}
						}
					}
				}
			}
		}
	},
	alertAttackableArea : function(isAlert){
		for( var i=0; i<this.attackUser.length; i++){
			var user = this.attackUser[i];
			var attackArea = document.getElementById(user + "_card_area");
			if(isAlert == 1){
				attackArea.style.border = "dotted 2px red";
			}
			else{
				attackArea.style.border = "";
			}
		}
	},
	_callbackArmCardDDEnd : function(e, id, metaInfo){
		if(this.isDoDropCard || this.isReceiveAttack 
			|| this.isDoPolicy || this.isDoSaving){
			return;
		}
		if( !this.checkDiscardable("arm") ){
			return;
		}
		var selectedCardId = metaInfo["card_id"];
		var selectedCard = this.getCardByCardId(selectedCardId);
		this.equipCardByDrag(selectedCard);
	},
	_callbackAttackCardDDEnd : function(userid, e, id, metaInfo, ddTarget){
		if(this.isDoDropCard || this.isReceiveAttack 
			|| this.isDoPolicy || this.isDoSaving){
			return;
		}
		if( !this.checkDiscardable("attack") ){
			return;
		}
		if(!this.selectedCard){
//			alert("first select your card!");
//			return;
		}
		var type = metaInfo["card_type"];
		var selectedCardId = metaInfo["card_id"];
		var selectedCard = this.getCardByCardId(selectedCardId);
		//alert(userid + " receive " + type + " card!");
		var receiveDiv = userid + "_card_receive_area";
		var conf = selectedCard.conf;
		conf.parentId = receiveDiv;
		var card = new ObjectCard();
		card.init(conf);
		card.drawUsedCard();
		var username = this.userMapArray[userid].name;
		this.discard(username, card);
		this.selectedCard = selectedCard;
		this.alertAttackableArea(0);
		this.waitReceive = true;
		setTimeout(this.clearAttackArea.bind(this, userid), 15000);
	},
	removeClientCard : function(){
		//redraw cards area
		if(this.selectedCard){
			this.removeAndrefreshCards(this.selectedCard.id, true);
			this.clearSelectedStyle();
		}
	},
	discard : function(targetId, card){
		var targetuser = new Array();
		targetuser[0] = targetId;
		var room = ComponentManager.getComponentById(this.roomId);
		var dataVersion = room.getDataVersion();
		RoomService.sendCard("current_player_instance", targetuser, card.cardId, dataVersion);
//		$('send_data_version').innerHTML = dataVersion;
		this.StopTheClock();
		//RoomService.sendCard(this.id, targetId, card.cardId);
	},
	doMatchCard : function(orignal, card){
		this.selectableCardType = card;
		alert("you receive " + orignal + "'s "+ card +" card!");
		if(card == "attack"){
			$('receive_message_area').innerHTML = "you receive " + orignal + "'s "+ card +" card! Please defend in 10 second!";
			this.InitializeTimer();
			this.isReceiveAttack = true;
			this.beSentUser = orignal;
			this.setActive(true);
		}
		//$('finish_play').disabled = false;
	},
	receiveDiscard : function(orignal, card){
		alert("receivediscard");
		alert("you receive " + orignal + "'s "+ card +" card!");
		if(card == "attack"){
			alert("you are under attack");
			$('receive_message_area').innerHTML = "you receive " + orignal + "'s "+ card +" card! Please defend in 10 second!";
			this.InitializeTimer();
			this.isReceiveAttack = true;
			this.beSentUser = orignal;
		}
		else if(card == "defend"){
			alert("defend yourself");
			var sendUserId = this.getUserIdByName(orignal);
			$(sendUserId + "_card_receive_area").innerHTML = "";
			this.waitReceive = false;
		}
	},
	InitializeTimer : function(){
	    // Set the length of the timer, in seconds
	    this.secs = 15;
	    this.StopTheClock();
	    this.StartTheTimer();
	},
	StopTheClock : function(){
	    if(this.timerRunning){
	        clearTimeout(this.timerID);
		    setTimeout(this.clearReceiveArea.bind(this), 2000);
	    }
	    this.timerRunning = false;
	},
	StartTheTimer : function (){
	    if (this.secs==0){
	        this.StopTheClock();
//	        alert("You have just wasted 10 seconds of your life.");
			this.setUserMessage("Time is over");
	        if(this.isReceiveAttack){
		        //this.cutLife();
				this.failToDoMatchCard();
	        }else if(this.isActive){
	        	this.finishPlay();
	        }
	    }
	    else{
	        if($('timer_area')){
		        $('timer_area').innerHTML = this.secs + "Second";
		        this.secs = this.secs - 1;
		        this.timerRunning = true;
		        this.timerID = setTimeout(this.StartTheTimer.bind(this), this.delay);
	        }
	    }
	},
	clearReceiveArea : function(){
		if($('user1_card_receive_area')){
			$('user1_card_receive_area').innerHTML = "";
		}
		if($('receive_message_area')){
	        $('receive_message_area').innerHTML = "";
		}
        if($('timer_area')){
	        $('timer_area').innerHTML = "";
        }
	},
	clearAttackArea : function(userid){
		if(this.waitReceive){
			$(userid + "_card_receive_area").innerHTML = "";
			this.waitReceive = false;
		}
	},
	errorHandlerOfFailMatch : function(){
		alert("Do match card maybe timeout, now will try again" );
		var room = ComponentManager.getComponentById(this.roomId);
		RoomService.failToMatchCard(this.id, this.receivedCard,
		{callback:function() {},
		  errorHandler:function(msg,ex) {
				alert("Error happened, Now is quiting");
				room.quit();
			}
		});
	},
	failToDoMatchCard : function(){
		this.isReceiveAttack = false;
		var room = ComponentManager.getComponentById(this.roomId);
		var dataVersion = room.getDataVersion();
//		$('send_data_version').innerHTML = dataVersion;
		var roomHandler = this;
		RoomService.failToMatchCard(this.id, this.receivedCard,
		{callback:function() {},
		  errorHandler:function(msg,ex) {
			  errorHandler:roomHandler.errorHandlerOfFailMatch.bind(roomHandler)
			}
		});
	},
	healLife : function(count){
		if(count == -1){
			$('hp_' + this.lifeCount).setStyle({background:'#FFFFFF'}); 
			this.lifeCount = this.lifeCount - 1;
			if(this.lifeCount == 0){
				alert("your will dead!");
			}
		}
		else if(count == 1){
			this.addLife();
		}
	},
	cutLife : function(){
		if(this.lifeCount == 0){
			alert("your lost!");
			return;
		}
	},
	addLife : function(){
		this.lifeCount += 1;
		var bgColor = "#FFFFFF";
		switch(this.lifeCount){
			case 1:
				bgColor = "#FF9900";
				break;
			case 2:
				bgColor = "#FF9900";
				break;
			case 3:
				bgColor = "#FF9900";
				break;
			case 4:
				bgColor = "#FF9900";
				break;
			case 5:
				bgColor = "#FF9900";
				break;
			default:
				bgColor = "#FF9900";
				break;
		}
		$('hp_' + this.lifeCount).setStyle({background:bgColor}); 
	},
	finishDiscard : function(){
		GameCenter.finishDiscard(this.id);
	},
	characterPolicy : function(policyId){
		alert('policyId' + policyId);
		if(this.isActive && !this.isDoPolicy){
			var obj = document.getElementById(policyId);
			obj.style.border = "inset"; 
			var room = ComponentManager.getComponentById(this.roomId);
			var dataVersion = room.getDataVersion();
			RoomService.enableCharacterPolicy(this.id, policyId, dataVersion);
			this.policyButtonId = policyId;
		}
	},
	selectPolicyCards : function(){
		this.isDoPolicy = true;
		if(this.cards){
			this.redrawCards(this.cardsContainerDivId, this.cards);
		}
		this.InitializeTimer();
		$('finish_play').disabled = false;
	},
	discardPolicyCards : function(){
		var room = ComponentManager.getComponentById(this.roomId);
		var targetuser = new Array();
		var tagUser = room.getSelectedUser();
		if(tagUser){
			targetuser[0] = tagUser.name;
		}
		else{
			targetuser[0] = this.user.name;
		}
		var cards = new Array();
		for(var i=0; i<this.selectedCards.length; i++){
			cards[i] = this.selectedCards[i].title;
		}
		var dataVersion = room.getDataVersion();
		RoomService.sendCardPolicy("current_player_instance", targetuser, cards, dataVersion);
//		$('send_data_version').innerHTML = dataVersion;
		$(this.policyButtonId).style.border = ""; 
		//RoomService.sendCard(this.id, targetId, card.cardId);
	},
	selectDropCards : function(dropCount){
		//$('finish_play').disabled = false;
		this.dropableCount = dropCount;
		//alert("please select " + this.dropableCount + " drop cards!");
		this.setUserMessage("please select " + this.dropableCount + " drop cards!");
		this.isDoDropCard = true;
		this.setActive(true);
		if(this.dropableCount == 0){
			this.dropCards();
		}
	},
	dropCards : function(cards){
		var room = ComponentManager.getComponentById(this.roomId);
		var dataVersion = room.getDataVersion();
		if(cards){
			var dCards = [];
			for(var i=0; i<cards.length; i++){
				dCards.push(cards[i].cardId);
				this.removeAndrefreshCards(cards[i].id, false);
			}
			RoomService.sendDropCards(this.id, dCards, dataVersion);
		}
		else{
			var dropCards = [];
			var dCards = [];
			for(var i=0; i<this.dropableCount; i++){
				var card = this.cards[i];
				dropCards.push(card);
				dCards.push(card.cardId);
			}
			RoomService.sendDropCards(this.id, dCards, dataVersion);
			for(var i=0; i<dropCards.length; i++){
				this.removeAndrefreshCards(dropCards[i].id, false);
			}
		}
		this.selectedCards = [];
		this.redrawCards(this.cardsContainerDivId, this.cards);
	},
	finishExecPolicy : function(){
		this.isDoPolicy = false;
	},
	finishDropCard : function(){
		this.isDoDropCard = false;
	},
	removeSelectedCard : function(){
		for(var i=0; i<this.selectedCards.length; i++){
			this.removeAndrefreshCards(this.selectedCards[i].id, false);
		}
		this.selectedCards = [];
	},
	getCardByCardId : function(cardId){
		for(var i=0; i<this.cards.length; i++){
			var card = this.cards[i];
			if(cardId == card.id){
				return card;
			}
		}
	},
	doUserRequestCard : function(orignal, card){
		var output=confirm("Are you want to discard "+card+" card?");
		if(output == true){
			RoomService.enableCharacterPolicy(this.id, orignal, card);
		}else{
			RoomService.enableCharacterPolicy(this.id, policyId, dataVersion);
		}
		 
	},
	refreshUserCard : function(cards){
		this.allCardCount = 0;
		this.cards = [];
		this.receiveCard(cards);
	},
	askSaveSelfExec : function(){
		alert("Your life is reduced to 0, please save self by milk card!");
		this.setActive(true);
		this.isDoSaving = true;
	},
	clearClientByDead : function(){
		$('user1_arm_card').innerHTML = "";
		$('user1_HP_card').innerHTML = "";
		$('user1_main_card').innerHTML = "The User is die!";
	},
	_callbackDoubleClickCard : function(event, message, componentId){
		for(var i=0; i<this.cards.length; i++){
			var div = this.cards[i];
			var element = document.getElementById(div.id);
			if(div.id == message.id){
				var element = document.getElementById(div.id);
				var armArea = document.getElementById("arm_card");
				if(this.isDoPolicy || this.isDoDropCard){
					var isExisted = false;
					for(var j=0; j<this.selectedCards.length; j++){
						if(this.cards[i].id == this.selectedCards[j].id){
							isExisted = true;
							break;
						}
					}
					if(!isExisted){
						this.selectedCards.push(this.cards[i])
						element.style.border = "solid 2px #0000ff";
					}
				}
				else{
					if(!this.selectedCard){
						this.selectedCard = this.cards[i];
						element.style.border = "solid 2px #0000ff";
						if(element.getAttribute("w:cardType") == "arm"){
							armArea.style.border = "dotted 2px #0000EE";
						}
						else{
							armArea.style.border = "solid 1px";
							//alert attack able area
							if(this.selectedCard.distance > 0){
								this.alertAttackableArea(1);
							}
						}
					}
				}
			}
		}
		this.okCard();
	},
	checkDiscardable : function(cardName){
		for(var j=0; j<this.activecards.length; j++){
			if( cardName == this.activecards[j]){
				return true;
			}
		}
		return false;
	}
});